package com.example.usermanagement.service;

import com.example.usermanagement.dto.JwtResponse;
import com.example.usermanagement.dto.LoginDTO;
import com.example.usermanagement.entity.UserLog;
import com.example.usermanagement.mapper.UserLogMapper;
import com.example.usermanagement.mapper.UserMapper;
import com.example.usermanagement.config.JwtTokenProvider;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class AuthService {

    private final AuthenticationManager authenticationManager;
    private final JwtTokenProvider tokenProvider;
    private final UserMapper userMapper;
    private final UserLogMapper userLogMapper;

    public AuthService(AuthenticationManager authenticationManager, JwtTokenProvider tokenProvider,
                       UserMapper userMapper, UserLogMapper userLogMapper) {
        this.authenticationManager = authenticationManager;
        this.tokenProvider = tokenProvider;
        this.userMapper = userMapper;
        this.userLogMapper = userLogMapper;
    }

    public JwtResponse authenticateUser(LoginDTO loginDTO) {
        System.out.println("开始认证: username=" + loginDTO.getUsername());
        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(loginDTO.getUsername(), loginDTO.getPassword()));
        SecurityContextHolder.getContext().setAuthentication(authentication);

        String token = tokenProvider.generateToken(authentication);
        String username = loginDTO.getUsername();
        String role = userMapper.findByUsername(username).get().getRole();

        // 记录登录日志
        UserLog log = new UserLog();
        log.setUserId(userMapper.findByUsername(username).get().getId());
        log.setAction("LOGIN");
        log.setTimestamp(LocalDateTime.now());
        userLogMapper.insert(log);

        JwtResponse response = new JwtResponse();
        response.setToken(token);
        response.setUsername(username);
        response.setRole(role);
        System.out.println("认证成功: username=" + username + ", token=" + token);
        return response;
    }
}